using CollabApp.Application.Interfaces;
using StackExchange.Redis;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;

namespace CollabApp.Infrastructure.Services;

/// <summary>
/// Redis 服务实现
/// 提供Redis数据库操作的具体实现，封装StackExchange.Redis的复杂性
/// </summary>
public class RedisService : IRedisService
{
    private readonly ConnectionMultiplexer _redis;
    private readonly IDatabase _database;

    public RedisService(string connectionString)
    {
        _redis = ConnectionMultiplexer.Connect(connectionString);
        _database = _redis.GetDatabase();
    }

    // Hash操作
    public async Task<Dictionary<string, string>> GetHashAllAsync(string key)
    {
        var result = await _database.HashGetAllAsync(key);
        return result.ToDictionary(x => x.Name.ToString(), x => x.Value.ToString());
    }

    public async Task<bool> HashSetAsync(string key, string field, string value)
    {
        return await _database.HashSetAsync(key, field, value);
    }

    public async Task<bool> HashDeleteAsync(string key, string field)
    {
        return await _database.HashDeleteAsync(key, field);
    }

    public async Task<string?> HashGetAsync(string key, string field)
    {
        return await _database.HashGetAsync(key, field);
    }

    public async Task SetHashMultipleAsync(string key, Dictionary<string, string> hash)
    {
        var hashEntries = hash.Select(kvp => new HashEntry(kvp.Key, kvp.Value)).ToArray();
        await _database.HashSetAsync(key, hashEntries);
    }

    public async Task SetHashAsync(string key, string field, string value)
    {
        await _database.HashSetAsync(key, field, value);
    }

    // List操作
    public async Task<List<string>> ListRangeAsync(string key, long start = 0, long stop = -1)
    {
        var result = await _database.ListRangeAsync(key, start, stop);
        return result.Select(x => x.ToString()).ToList();
    }

    public async Task<long> ListLeftPushAsync(string key, string value)
    {
        return await _database.ListLeftPushAsync(key, value);
    }

    public async Task<long> ListRightPushAsync(string key, string value)
    {
        return await _database.ListRightPushAsync(key, value);
    }

    public async Task<string?> ListLeftPopAsync(string key)
    {
        return await _database.ListLeftPopAsync(key);
    }

    public async Task<string?> ListRightPopAsync(string key)
    {
        return await _database.ListRightPopAsync(key);
    }

    public async Task<long> ListPushAsync(string key, string value)
    {
        return await _database.ListLeftPushAsync(key, value);
    }

    // Set操作
    public async Task<HashSet<string>> GetSetMembersAsync(string key)
    {
        var result = await _database.SetMembersAsync(key);
        return result.Select(x => x.ToString()).ToHashSet();
    }

    public async Task<bool> SetAddAsync(string key, string value)
    {
        return await _database.SetAddAsync(key, value);
    }

    public async Task<bool> SetRemoveAsync(string key, string value)
    {
        return await _database.SetRemoveAsync(key, value);
    }

    public async Task<bool> SetContainsAsync(string key, string value)
    {
        return await _database.SetContainsAsync(key, value);
    }

    public async Task<long> GetSetCardinalityAsync(string key)
    {
        return await _database.SetLengthAsync(key);
    }

    // String操作
    public async Task<bool> StringSetAsync(string key, string value, TimeSpan? expiry = null)
    {
        return await _database.StringSetAsync(key, value, expiry);
    }

    public async Task<string?> StringGetAsync(string key)
    {
        return await _database.StringGetAsync(key);
    }

    public async Task<bool> KeyDeleteAsync(string key)
    {
        return await _database.KeyDeleteAsync(key);
    }

    public async Task<bool> KeyExistsAsync(string key)
    {
        return await _database.KeyExistsAsync(key);
    }

    // 过期时间
    public async Task<bool> KeyExpireAsync(string key, TimeSpan expiry)
    {
        return await _database.KeyExpireAsync(key, expiry);
    }

    public async Task<bool> SetExpireAsync(string key, TimeSpan expiry)
    {
        return await _database.KeyExpireAsync(key, expiry);
    }

    // 新增的接口方法实现
    public async Task<bool> DeleteHashAsync(string key, string field)
    {
        return await _database.HashDeleteAsync(key, field);
    }

    public async Task<string?> GetStringAsync(string key)
    {
        return await _database.StringGetAsync(key);
    }

    public async Task<bool> ExistsAsync(string key)
    {
        return await _database.KeyExistsAsync(key);
    }

    public async Task<bool> SetStringAsync(string key, string value, TimeSpan? expiry = null)
    {
        return await _database.StringSetAsync(key, value, expiry);
    }

    public async Task<bool> ExpireAsync(string key, TimeSpan expiry)
    {
        return await _database.KeyExpireAsync(key, expiry);
    }

    public async Task<T?> GetAsync<T>(string key) where T : class
    {
        var value = await _database.StringGetAsync(key);
        if (!value.HasValue)
            return null;
        
        try
        {
            return System.Text.Json.JsonSerializer.Deserialize<T>(value.ToString());
        }
        catch
        {
            return null;
        }
    }

    public async Task<bool> SetAsync<T>(string key, T value, TimeSpan? expiry = null) where T : class
    {
        if (value == null)
            return false;
        
        try
        {
            var json = System.Text.Json.JsonSerializer.Serialize(value);
            return await _database.StringSetAsync(key, json, expiry);
        }
        catch
        {
            return false;
        }
    }

    // ZSet操作
    public async Task<bool> SortedSetAddAsync(string key, string member, double score)
    {
        return await _database.SortedSetAddAsync(key, member, score);
    }

    public async Task<List<(string member, double score)>> SortedSetRangeByRankWithScoresAsync(string key, long start, long stop, bool descending = true)
    {
        var order = descending ? Order.Descending : Order.Ascending;
        var entries = await _database.SortedSetRangeByRankWithScoresAsync(key, start, stop, order);
        return entries.Select(e => (e.Element.ToString(), e.Score)).ToList();
    }

    public async Task<double?> SortedSetScoreAsync(string key, string member)
    {
        return await _database.SortedSetScoreAsync(key, member);
    }

    public async Task<long?> SortedSetRankAsync(string key, string member, bool descending = true)
    {
        return descending
            ? await _database.SortedSetRankAsync(key, member, Order.Descending)
            : await _database.SortedSetRankAsync(key, member, Order.Ascending);
    }

    public async Task<bool> SortedSetRemoveAsync(string key, string member)
    {
        return await _database.SortedSetRemoveAsync(key, member);
    }

    // 资源释放
    public void Dispose()
    {
        _redis?.Dispose();
    }
}